package org.jiucheng.magpiebridge.manager.util;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.MessageFormat;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jiucheng.magpiebridge.manager.entity.Server;
import org.jiucheng.magpiebridge.protocol.Message;

/**
 * 通知server
 * 
 * @author jiucheng
 *
 */
public class ServerNotify {
    public static void notify(final Server server, final String clientKey) {
        ExecutorService es = Executors.newSingleThreadExecutor();
        es.execute(new Runnable() {
            public void run() {
                try {
                    Socket socket = new Socket(server.getIp(), server.getPort());
                    OutputStream os = socket.getOutputStream();
                    Message message = new Message();
                    message.setData(MessageFormat.format("{0}#{1}", server.getToken(), clientKey).getBytes());
                    message.setSize(message.getData().length);
                    message.setMagic(Message.MAGIC);
                    message.setType(Message.Type.PROXYRESET);
                    os.write(Message.toByteBuffer(message).array());
                    os.close();
                    socket.close();
                } catch (UnknownHostException e) {
                    // e.printStackTrace();
                } catch (IOException e) {
                    // e.printStackTrace();
                }
            }
        });
        es.shutdown();
    }
}
